package com.kfh.ybracelet.utils;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

public class JpushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPushReceiver";

    public static final String MESSAGE_RECEIVED_ACTION = "com.kfh.ybracelet.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static String uid = "";
    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {

        LogUtil.e("jpush", "收到了一条消息=================>");

        if (context == null || intent == null)
            return;

        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;

        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        LogUtil.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            LogUtil.d(TAG, "JPush用户注册成功");

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            LogUtil.d(TAG, "接受到推送下来的自定义消息");
//	            receivingNotification(context,bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            LogUtil.d(TAG, "接受到推送下来的通知");

//	            receivingNotification(context,bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            LogUtil.d(TAG, "用户点击打开了通知");

            openNotification(context, bundle);

        } else {
            LogUtil.d(TAG, "Unhandled intent - ACTION ==>" + intent.getAction());
        }

    }

    //	 private void receivingNotification(Context context, Bundle bundle){
//	        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
//	        LogUtil.d(TAG, " title : " + title);
//	        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//	        LogUtil.d(TAG, "message : " + message);
//	        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//	        LogUtil.d(TAG, "extras : " + extras);
//
//	        //通知栏打开通知
//	    	NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
//			Notification notify = new Notification();
//			// 设置通知在状态栏显示的图标
//			notify.icon = R.drawable.ic_launcher;
//			// 通知时发出的声音
//			notify.defaults = Notification.DEFAULT_SOUND;
//
//			Intent intent = new Intent(context, StartActivity.class);
//			//context.getPackageName().equals(getRunningPackageName(context)) ? null :
//			PendingIntent contentIntent = PendingIntent.getActivity(context, 0,intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//			notify.setLatestEventInfo(context, TextUtils.isEmpty(title) ? "新消息" : title, message, contentIntent);
//
//			nManager.notify(0, notify);
//
//	    }
//
    private void openNotification(Context context, Bundle bundle) {
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String myValue = "";
        try {
            JSONObject extrasJson = new JSONObject(extras);
            myValue = extrasJson.optString("myKey");

            LogUtil.e("jpush", "===================openNotification==========");
            //用户未打开我们的应用
            if (!context.getPackageName().equals(getRunningPackageName(context))) {
                PackageManager packageManager = context.getPackageManager();
                Intent intent = new Intent();
                try {
                    intent = packageManager.getLaunchIntentForPackage("com.kfh.ybracelet");
                } catch (Exception e) {
                    LogUtil.e(TAG, e.toString());
                }
                context.startActivity(intent);
            }

        } catch (Exception e) {
            LogUtil.e("jpush", "Unexpected: extras is not a valid json");
            return;
        }
    }

    // 打印所有的 intent extra 数据
    private String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 获得当前运行的app的包名
     *
     * @return
     */
    private String getRunningPackageName(Context ctx) {
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
        return packageName;
    }
//
//	private void openMessageActivity(Context context, Bundle bundle) {
//		
//		
//		
//		// 打开自定义的Activity 	TODO
////		if (MainActivity.instance != null) {
////			// 打开消息中心
////			MainActivity.instance.switchCurrentFragment(2);
////		}
//	}
//
//	// send msg to MainActivity
//	private void processCustomMessage(Context context, Bundle bundle) {
//		MessageInfo msg = new MessageInfo();
//		try {
//			String msg_id = bundle.getString(JPushInterface.EXTRA_MSG_ID);
//			String alert = bundle.getString(JPushInterface.EXTRA_ALERT);
//			String title = bundle.getString(JPushInterface.EXTRA_TITLE);// 自定义标题
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			// String push_time = bundle.getString(JPushInterface.EXTRA_);
//
//			msg.setMsg_id(msg_id);
//			msg.setAlert(alert);
//			msg.setTitle(title);
//			// msg.setPush_time(push_time);
//
//			Intent msgIntent = new Intent(MESSAGE_RECEIVED_ACTION);
//
//			 if (extras != null && extras.length() > 0) {
//			
//			 JSONObject extraJson = JSON.parseObject(extras);
//			 if (null != extraJson) {
//			 // msgIntent.putExtra(KEY_EXTRAS, extras);
//			
//			 String msg_body_type = extraJson.getString("msg_body_type");
//			 String msg_sub_type = extraJson.getString("msg_sub_type");
//			 String push_time = extraJson.getString("push_time");
//			 String content = extraJson.getString("url");
//			
////			 msg.setMsg_body_type(msg_body_type);
////			 msg.setMsg_sub_type(msg_sub_type);
////			 msg.setPush_time(push_time);
////			 msg.setContent(content);
//			 }
//			 }
//
//			// 存数据库
//			// MessageInfoDatabase.save(context, msg, uid );
//			msgIntent.putExtra("message", msg);
//
//			LogUtil.e("TAG", "极光推送的消息========>" + msg.toString());
//
//			context.sendBroadcast(msgIntent);
//		} catch (Exception e) {
//			Log.e("JPushReceiver", e.toString());
//		}
//	}
}
